// pages/address/address.js
const app = getApp()
const { getUserAllAddress, updateAddress, changeUserDefaultAddress, addNewAddress, deleteUserAddress } = require("../../utils/api");
import Dialog from '@vant/weapp/dialog/dialog';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    header: {
      title: '收货地址',
      whiteBg: false,
      mode: 'back',
      navBarHeight: app.globalData.navBarHeight
    },

    userInfo: {},
    modifyAddressPopup: false,
    addNewAddressPopup: false,
    isBg: false,
    selectedAddressIndex: null,
    address: [],
    newAddress: {
      default: false,
      receivePhoneNumber: null,
      receiverName: null,
      receiveAddress: null,
    },
  },

  onLoad(options) {
    this.setData({
      userInfo: wx.getStorageSync('userInfo')
    })
    if (options.addNewAddressPopup) {
      this.setData({
        addNewAddressPopup: options.addNewAddressPopup === 'true',
      });
    }
    this.getUserAllAddress()
  },

  onPageScroll(e) {
    this.setData({
      'header.whiteBg': e.scrollTop < 40 ? false : true
    })
  },

  getUserAllAddress() {
    getUserAllAddress({PhoneNumber: this.data.userInfo.phoneNumber}).then(res => {
      if (res.code === 4007010) {
        this.setData({
          address: res.data
        })
      } else {
        wx.showToast({
          title: '地址获取失败' + res.msg,
        })
      }
    });
  },

  changeModifyAddressPopup(e){
    if (e !== undefined) {
      this.setData({
        selectedAddressIndex: e.currentTarget.dataset.index
      })
    }
    this.setData({ 
      modifyAddressPopup: !this.data.modifyAddressPopup,
    })
  },

  changeAddAddressPopup() {
    if (this.data.addNewAddressPopup) {
      this.setData({
        newAddress: {
          default: null,
          receivePhoneNumber: null,
          receiveAddress: null,
          receiverName: null,
        },
      })
    }
    this.setData({
      addNewAddressPopup: !this.data.addNewAddressPopup
    })
  },

  changeDafaultAddress(e) {
    changeUserDefaultAddress({ PhoneNumber: this.data.userInfo.phoneNumber,
    AddressNumber: this.data.address[e.currentTarget.dataset.index].addressNumber}).then(res =>{
      if(res.code === 4007020) {
        const path = 'address[' + e.currentTarget.dataset.index + '].Default'
        const address = this.data.address.map(item =>{
          return {
            ...item,
            Default: 0
          }
        })
        this.setData({
          address: address,
          [path]: 1
        })
        this.getUserAllAddress();
      }else {
        wx.showToast({
          title: '切换失败' + res.msg,
          icon: 'none'
        })
      }
    })
  },

  inputModifyAddress(e) {
    const path = 'address[' + this.data.selectedAddressIndex + '].' + e.currentTarget.dataset.value
    this.setData({
      [path]: e.detail.value
    })
  },

  inputCreateAddress(e) {
    const path = 'newAddress.' + e.currentTarget.dataset.value
    this.setData({
      [path]: e.detail.value
    })
  },

  changeNewAddressDefault() {
    this.setData({
      'newAddress.default' : !this.data.newAddress.default
    })
  },

  onPageScroll(e) {
    this.setData({
      isBg: e.scrollTop < 40 ? false : true
    })
  },

  submitModifyAddress(){
    const data = {
      PhoneNumber: this.data.userInfo.PhoneNumber,
      AddressNumber: this.data.address[this.data.selectedAddressIndex].AddressNumber,
      UserPhoneNumber: this.data.address[this.data.selectedAddressIndex].UserPhoneNumber,
      Address: this.data.address[this.data.selectedAddressIndex].Address,
      Default: this.data.address[this.data.selectedAddressIndex].Default,
      UserName: this.data.address[this.data.selectedAddressIndex].UserName
    }
    updateAddress(data).then(res =>{
      if (res.code === 4007050) {
        wx.showToast({
          title: '修改成功',
          icon: 'none'
        })
      }else{
        wx.showToast({
          title: '修改失败请重试' + res.msg,
          icon: 'none'
        })
      }
    });
    this.changeModifyAddressPopup();
  },

  submitNewAddress() {
    if (this.data.newAddress.receivePhoneNumber === null || 
      this.data.receiverName === null ||
      this.data.receiveAddress === null ||
      this.data.newAddress.receivePhoneNumber === '' || 
      this.data.receiverName === '' ||
      this.data.receiveAddress === '') {
        wx.showToast({
          title: '请勿留空，请全部填写',
          icon: 'none'
        })
        return
      }
    addNewAddress({
      PhoneNumber: this.data.userInfo.phoneNumber,
      UserPhoneNumber: this.data.newAddress.receivePhoneNumber,
      Address: this.data.newAddress.receiveAddress,
      Default: this.data.newAddress.default ? 1 : 0,
      UserName: this.data.newAddress.receiverName
    }).then(res =>{
      if (res.code === 4007040) {
        wx.showToast({
          title: '添加成功',
        })
        this.getUserAllAddress()
        this.changeAddAddressPopup()
      }else {
        wx.showToast({
          title: '添加失败' + res.msg,
          icon: 'none'
        })
      }
    })
  },

  deleteAddress(e) {
    Dialog.confirm({
      message: '确认要删除该地址吗？',
      theme: 'round-button',
      showCancelButton: true,
    })
      .then(() => {
        // 调用删除接口
        return deleteUserAddress({
          PhoneNumber: this.data.userInfo.phoneNumber,
          AddressNumber: this.data.address[e.currentTarget.dataset.index].addressNumber,
        });
      })
      .then((res) => {
        if (res.code === 4007030) {
          wx.showToast({
            title: '删除成功',
          });
          this.getUserAllAddress()
        } else {
          wx.showToast({
            title: '删除失败: ' + res.msg,
            icon: 'none',
          });
        }
      })
      .catch((err) => {
        console.error('操作取消或发生错误:', err);
      });
    
  }
})